/*
 * @Description: In User Settings Edit
 * @Author: gyc
 * @Date: 2019-09-28 20:39:27
 * @LastEditTime: 2019-10-02 12:39:00
 * @LastEditors: Please set LastEditors
 */
let OSS = require('ali-oss');
let fs = require('fs');

let client = new OSS({
  region: 'oss-cn-hangzhou',
  //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
  accessKeyId: 'LTAIp6SMnRobIrI1',
  accessKeySecret: '7dvADSzKSnAJTxB5SmLQ98OtbLcuH2',
  bucket: 'pubmosa'
});

async function myDir(dir) {
  let signUrl = client.signatureUrl(dir, { expires: 86400 });
  // console.log(signUrl);
  return signUrl
}

async function put(name, file) {
  try {
    //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
    let result = await client.put('avatar/' + name, file);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}
// myDir('sao.mp4')
async function putStream(name, file) {
  try {
    // use 'chunked encoding'
    // let stream = fs.createReadStream(file);
    // let result = await client.putStream(name, stream);
    // console.log(result);

    // don't use 'chunked encoding'
    let stream = fs.createReadStream(file);
    let size = fs.statSync(file).size;
    let result = await client.putStream(
      name, stream, { contentLength: size });
    console.log(result);
  } catch (e) {
    console.log(e)
  }
}

module.exports = { myDir, put, putStream }